<template>
  <div>
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="用户昵称" prop="nickName">
        <el-input v-model="form.nickName" maxlength="30" />
      </el-form-item>
      <el-form-item label="手机号码" prop="phonenumber">
        <el-input v-model="form.phonenumber" maxlength="11" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" maxlength="50" />
      </el-form-item>
      <el-form-item label="性别">
        <el-radio-group v-model="form.sex">
          <el-radio label="0">男</el-radio>
          <el-radio label="1">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="微信">
        <span class="mr10">{{ form.wxnickname || "未绑定" }}</span>
        <el-button
          v-if="form.openid == '' || form.openid == null"
          :loading="bindloading"
          size="medium"
          type="primary"
          class="btn"
          @click.stop="wxBind()"
          >绑 定</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" @click="submit">保存</el-button>
        <el-button type="danger" size="mini" @click="close">关闭</el-button>
      </el-form-item>
    </el-form>

    <el-dialog
      title="绑定微信"
      custom-class="bind-dialog"
      class="new-common-dialog"
      :visible.sync="bindWxVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="wxLoginClose"
      width="320px"
    >
      <div class="qr-code">
        <img :src="qrUrl" class="qr-code-img" alt="扫码绑定" />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { updateUserProfile, getUUid } from "@/api/system/user";
import { getToken } from "@/utils/auth";

export default {
  props: {
    user: {
      type: Object,
    },
  },
  data() {
    return {
      form: {},
      // 表单校验
      rules: {
        nickName: [
          { required: true, message: "用户昵称不能为空", trigger: "blur" },
        ],
        email: [
          { required: true, message: "邮箱地址不能为空", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        phonenumber: [
          { required: true, message: "手机号码不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
      },
      timer: null,
      bindWxVisible: false,
      bindloading: false,
      qrUrl: "",
    };
  },
  watch: {
    user: {
      handler(user) {
        if (user) {
          this.form = {
            nickName: user.nickName,
            wxnickname: user.wxNickName,
            phonenumber: user.phonenumber,
            email: user.email,
            sex: user.sex,
            openid: user.openid,
          };
        }
      },
      immediate: true,
    },
  },
  methods: {
    submit() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          updateUserProfile(this.form).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.user.phonenumber = this.form.phonenumber;
            this.user.email = this.form.email;
          });
        }
      });
    },
    close() {
      this.$tab.closePage();
    },
    wxBind() {
      this.bindloading = true;
      let token = getToken();
      const key = JSON.parse(atob(token.split(".")[1]))["login_user_key"];

      // 后端端口映射
      const backendBaseUrl = "http://l9ahqakkef0e.vip3.xiaomiqiu123.top";
      // 使用后端生成的二维码
      this.qrUrl = `${backendBaseUrl}/wx/qr-bindImg?key=${key}`;
      this.bindWxVisible = true;
      this.bindloading = false;

      let that = this;
      this.timer = setInterval(function () {
        getUUid({
          uuid: key,
        })
          .then((res) => {
            if (res.status === 1) {
              that.bindWxVisible = false;
              that.form.openid = res.openid;
              that.form.wxnickname = res.wxnickname;
              that.$message({
                type: "success",
                message: "绑定成功",
              });
              clearInterval(that.timer);

              // 提交用户信息更新，确保数据同步
              that.submit();
            }
          })
          .catch((err) => {
            clearInterval(that.timer);
          });
      }, 1000);
    },
    wxLoginClose() {
      this.timer && clearInterval(this.timer);
    },
  },
};
</script>

<style scoped>
.mr10 {
  margin-right: 10px;
}
.qr-code {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px 0;
}
.qr-code-img {
  height: 280px;
}
.bind-dialog .el-dialog__body {
  padding: 10px 20px;
}
</style>
